<%
available_client_versions = MicrosoftProjectConnectorController.helpers.available_client_versions
redmine_columns = MicrosoftProjectConnectorController.helpers.available_redmine_columns

temp_query = IssueQuery.new
not_inline_column_names = temp_query.available_columns.select{|c| !c.inline?}.map{|c| c.name}

on_task_delete_options = [
    [l(:on_task_delete_none), ''],
    [l(:on_task_delete_ask), 'askme'],
    [l(:on_task_delete_delete), 'delete']
]
%>

<div>
    <h3 style="float: left"><%=l(:columns_mapping)%></h3>

    <div style="float: right;line-height: 1.5rem">
        <span><%=l(:new_mapping)%> </span>
        <%= select_tag 'available_columns',
        options_for_select([['', '']] + redmine_columns.map{|c| [c[:label], c[:name]]}),
        :id => 'select_redmine_columns'%>
    </div>
    <div style="float: right; clear: both"></div>
</div>

<table class="list">
    <thead>
        <tr>
            <th><%=l(:redmine_column)%></th>
            <th><%=l(:project_column)%></th>
            <th><%=l(:label_enumerations)%></th>
            <th>
                
            </th>
        </tr>
    </thead>
    <tbody id="body_mapping">

    </tbody>
</table>

<div>
    <br/>
    <h3 style="float: left"><%=l(:on_task_delete)%>:</h3>
    <div style="float: left;line-height: 1.5rem">
         <%= select_tag 'settings[on_task_delete]', options_for_select(on_task_delete_options, Setting["plugin_microsoft_project_connector"]['on_task_delete']) %>
    </div>
    <div style="clear: both"></div>
</div>

<script>
    var MSPFieldS = <%= MicrosoftProjectConnectorController.helpers.available_msp_fields.to_json.html_safe %>;
    var RedmineColumns = <%= redmine_columns.to_json.html_safe %>;
    var ColumnTitles = '<%= l(:task_column_titles) %>'.split('||');
    var NotInlineColumnNames = '<%=not_inline_column_names.to_json.html_safe %>';
    var PRESERVE_FIELDS = ['id', 'assigned_to'];

    $.each(<%=MicrosoftProjectConnectorController.helpers.msc_columns_mapping_settings.to_json.html_safe %>, function(i, o) {
        var redmineColumn = RedmineColumns.find(function(rc) {
            return rc.name == o.redmine;
        });

        if (redmineColumn) {
            mspAddColumnMapping(redmineColumn.name, redmineColumn.msp_field);
            disabledMspOption(redmineColumn.msp_field, true);
        }
    });

    $('#select_redmine_columns').change(function(e) {
        var val = e.currentTarget.value;
        if (val) {
            mspAddColumnMapping(val);
        }
    });

    $('#body_mapping').delegate('.btn_remove_mapping', 'click', function(e) {
        e.preventDefault();

        if (confirm('<%=l(:text_are_you_sure)%>')) {
            var $tr =  $(e.currentTarget).closest('tr');
            $('#select_redmine_columns option[value="' + $tr.data('field') + '"]').prop('disabled', false);

            var mspField = $tr.find('.select_msp_field').val();
            if (mspField) {
                disabledMspOption(mspField, false);
            }
            $tr.remove();

        }
    }).delegate('.select_msp_field', 'change', function(e) {
        var currentTarget = e.currentTarget;
        var value = currentTarget.value;
        if (value) {
            disabledMspOption(value, true);
        }
        
        var oldValue = $(currentTarget).data('ov');
        if (oldValue) {
            disabledMspOption(oldValue, false);
        }

        $(currentTarget).data('ov', value || '');

        if (value) {
            const mspField = MSPFieldS.find(function (f) {
                return f.name === value;
            });

            if (mspField && mspField.type === 'enum') {
                const redmineColumnName = $(currentTarget).closest('td').prev('td').find('input[name="settings[mpc_columns_mapping][][redmine]"]').val();
                const redmineColumn = RedmineColumns.find(function(c) {return c.name === redmineColumnName});

                if (redmineColumn) {
                    const redmineItems = redmineColumn.possible_values || [];
                    const mspItems = mspField.enum_items || []
                    const itemLength = Math.max(mspItems.length, redmineItems.length);

                    const enumMappingText = [];
                    for (let i = 0; i < itemLength; i++) {
                        enumMappingText.push((redmineItems[i] || 'NULL') + '->' + (mspItems[i] || 'null'));
                    }

                    const inlineStyle = redmineItems.length !== mspItems.length ? 'color: red' : '';

                    $(currentTarget).closest('td').next('td').html('<div style="' + inlineStyle + '">' + enumMappingText.join("; ") + '</div>');
                }
            }
        } else {
            $(currentTarget).closest('td').next('td').html('');
        }
    });

    function mspAddColumnMapping(columnName, mspFieldName) {
        var redmineColumn = RedmineColumns.find(function(rc) {
            return rc.name == columnName;
        });
        var html = '<tr data-field="' + columnName + '">';
        html += '<td>' + (redmineColumn && redmineColumn.label) + ' <input type="hidden"  name="settings[mpc_columns_mapping][][redmine]" value="' + columnName + '"/></td>';
        html += '<td>';
        if(PRESERVE_FIELDS.indexOf(columnName) === -1 || !mspFieldName) {
            html += '<select class="select_msp_field" data-ov="' + (mspFieldName || '') + '" name="settings[mpc_columns_mapping][][msp]">' + generateMspOptions(redmineColumn, mspFieldName) + '</select>';
        } else {
            var mspField = MSPFieldS.find(function(f) {
                return f.name === mspFieldName;
            });
            html += ColumnTitles[mspField.title_index] + '<input type="hidden" name="settings[mpc_columns_mapping][][msp]" value="' + mspFieldName + '" />';
        }
        html += '</td>';
        html += '<td></td>';
        html += '<td class="operation">';
        html += '<span class="sort-handle"></span>';
        if(PRESERVE_FIELDS.indexOf(columnName) === -1) {
            html += '&nbsp;&nbsp;&nbsp;<a href="#" class="btn_remove_mapping icon icon-del">&nbsp;</a>';
        }
        html += '</td>';
        html += '</tr>';
        $('#body_mapping').append(html);

        $('#select_redmine_columns option[value="' + columnName + '"]').prop('disabled', true);
    }

    function generateMspOptions(redmineColumn, selectedMspFieldName) {
        if (NotInlineColumnNames.includes(redmineColumn.name)) {
            var usedMspFields = getUsedMspFields();

            //multiple line only can map to Notes
            return ([{name: ''}].concat(MSPFieldS.filter(function(f) {
                return f.name == 'Notes';
            }))).map(function(f) {
                return '<option value="' + f.name + '" ' + (selectedMspFieldName && selectedMspFieldName === f.name ? 'selected' : '') + ' ' + (usedMspFields.indexOf(f.name) === -1 ? '' : 'disabled') + '>' + (ColumnTitles[f.title_index] || '') + (f.readonly ? ' (<%=l(:label_readonly)%>)' : '') + '</option>';
            }).join('');
        }

        var acceptFormats;

        var format = redmineColumn.field_format || 'string';
        switch(format) {
            case 'string':
                if (redmineColumn.cf_field_format == 'enumeration' || redmineColumn.cf_field_format == 'list') {
                    acceptFormats = ['string', 'enum']
                } else {
                    acceptFormats = ['string']
                }
                break;
            case 'text':
            case 'link':
                acceptFormats = ['string'];
                break;
            case 'int':
                acceptFormats = ['short', 'int', 'double'];
                break;
            case 'float':
                acceptFormats = ['int', 'double'];
                break;
            case 'date':
                acceptFormats = ['DateTime'];
                break;
            case 'bool':
                acceptFormats = ['bool'];
                break;
        }

        if (!acceptFormats) {
            return '';
        }

        var usedMspFields = getUsedMspFields();

        return ([{name: ''}].concat(MSPFieldS.filter(function(f) {
            return acceptFormats.indexOf(f.type) !== -1;
        }))).map(function(f) {
            return '<option value="' + f.name + '" ' + (selectedMspFieldName && selectedMspFieldName === f.name ? 'selected' : '') + ' ' + (usedMspFields.indexOf(f.name) === -1 ? '' : 'disabled') + '>' + (ColumnTitles[f.title_index] || '') + (f.readonly ? ' (<%=l(:label_readonly)%>)' : '') + '</option>';
        }).join('');
    }

    function getUsedMspFields() {
        return $('#body_mapping [name="settings[mpc_columns_mapping][][msp]"]').toArray().map(function(s) {
            return s.value;
        }).filter(function(f) {
            return !!f;
        })
    }

    function disabledMspOption(fieldName, disabled) {
        $('#body_mapping .select_msp_field').each(function(i, o) {
            if (o.value !== fieldName) {
                for(var i = 1; i < o.options.length; i++) {
                    if (o.options[i].value == fieldName) {
                        o.options[i].disabled = disabled;
                    }
                }
            }
        });
    }

    $(function() {
        $('#settings [name=commit]').parent().append('&nbsp;&nbsp;<a href="http://conveniencable.com/download/msprc/<%=available_client_versions[available_client_versions.length - 1]%>"><%=l(:button_download_msp_plugin)%></a>')

        var $columnsBody = $('#body_mapping');
        $columnsBody.sortable($.extend({
            axis: 'y',
            handle: ".sort-handle",
            helper: function(event, ui){
                ui.children('td').each(function(){
                $(this).width($(this).width());
                });
                return ui;
            }
        }, {}));

        $('select.select_msp_field').trigger('change');
    });

</script>
<style>
.sort-handle {
    display: inline-block;
    width: 16px;
    height: 16px;
    background: url(/images/reorder.png) no-repeat 0 50%;
    cursor: move;
}

table.list th,
table.list td{
    padding: 3px 5px;
    text-align: left;
}

table.list td.operation {
    width: 1px;
    white-space: nowrap;
}

</style>

<% html_title(l(:label_settings), l(:labe_corp_wechats)) -%>